import useModalSize from "./useModalSize"
import { ElMessageBox } from 'element-plus'

let id = 0

const nextId = () => {
    return ++id
}

const afterOpened = (ele) => {
    const btns = ele.querySelector(".el-message-box__btns").children
    let removeBtns = true
    for (const btn of btns) {
        if (getComputedStyle(btn).display !== 'none') removeBtns = false
    }
    if (removeBtns) {
        ele.querySelector(".el-message-box__btns").remove()
    }
    ele.querySelector(".el-message-box__input").remove()
}

const useElMessageBox = (title, message, option = {}) => {
    const { customClass = "", type = "info", falseInCatch = true, showCancelButton = false, closeOnClickModal = false, ignoreCancel = true,
        beforeClose = null, showIcon = true, replaceNewline = false, showClose = false, showConfirmButton = true, onOpened = () => void 0 } = option
    const messageboxId = "messagebox-" + nextId()
    const messageOptions = {
        confirmButtonText: ' ',
        cancelButtonText: ' ',
        type,
        showConfirmButton,
        showCancelButton,
        customClass: `use-el-message-box ${messageboxId} ${customClass} ${showIcon ? "" : "hidden-icon"} forbid-select`,
        closeOnClickModal,
        cancelButtonClass: "iconfont icon-close button-auto-resize",
        confirmButtonClass: 'iconfont icon-check button-auto-resize',
        roundButton: true,
        showClose,
        showInput: false,
        beforeClose,
        distinguishCancelAndClose: true,
        dangerouslyUseHTMLString: true
    }
    useModalSize()
    if (replaceNewline) message = message.replace(/\n/g, '<br/>')

    return new Promise((resolve, reject) => {
        ElMessageBox({ title, message, ...messageOptions }).then((e) => {
            resolve(e)
        }).catch((e) => {
            if (!ignoreCancel) falseInCatch ? reject(e) : resolve(e)
        }).finally(() => {
            useModalSize(false)
        })
        setTimeout(() => {
            const ele = document.querySelector(`.${messageboxId}`)
            afterOpened(ele)
            onOpened(ele)
        })
    })
}

["success", "warning", "info", "error"].forEach(type => {
    useElMessageBox[type] = (message, title, option = {}) => {
        option.type = type
        return useElMessageBox(message, title, option)
    }
})

export default useElMessageBox